package com.howard.action;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.howard.entity.User;
import com.howard.exception.BeanPropertyExcpetion;
import com.howard.exception.ServiceException;
import com.howard.service.UserService;

/**
 *
 * @author <a href="mailto:howard.he0329@gmail.com">Howard He</a>
 *
 */
@Controller
@RequestMapping("/userinfo")
public class UserController {

	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
	public String getUser(@PathVariable("userId") Long userId, Model model)
			throws ServiceException {
		User user = userService.searchUserById(userId);
		model.addAttribute(user);
		return "/userinfo/userinfo";
	}

	@RequestMapping(value = "/doAddUser")
	public String doAddUser(User user, Model model) throws ServiceException, BeanPropertyExcpetion {
		if(logger.isDebugEnabled())
			logger.debug("User: " + user);
		user.validate();
		long id = 0;
		id = userService.addUser(user);
		// redirect 重定向 "/" 开头为当前项目根路径 ，不以"/"是以相对于当前路径
		return "redirect:/userinfo/" + id;
	}

	@RequestMapping(value = "/add")
	public String addUser(User user, Model model) {
		if(logger.isDebugEnabled()) {
			logger.debug(this.getClass().getSimpleName() + ": " + this);
		}
		return "/userinfo/addUser";
	}

	@RequestMapping(value = "/list")
	public String doList(Model model) throws ServiceException {
		List<User> userList = userService.searchUserForList();
		model.addAttribute(userList);
		return "/userinfo/userList";
	}

	@RequestMapping(value = "/{userId}/delete")
	public String doDelete(@PathVariable Long userId) throws ServiceException {
		userService.delUser(userId);
		return "redirect:/userinfo/list";
	}
}
